package xin.nick.common.core.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.annotation.PostConstruct;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常过滤器
 * @author Nick
 * @since 2023/11/26
 */

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(value = "/*",filterName ="GlobalExceptionFilter" )
@RequiredArgsConstructor
@Slf4j
public class GlobalExceptionFilter extends OncePerRequestFilter {

    private final HandlerExceptionResolver handlerExceptionResolver;

    @PostConstruct
    public void initMethod() {
      log.info("全局异常过滤器创建....");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            // 就正常处理就行
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            // 有异常了交给全局异常处理
            handlerExceptionResolver.resolveException(request, response, null, e);
        }
    }
}
